<template>
	<view class="userpost userIndex" :class="[isDark?'dark':'', $store.state.AppStyle]" :style="{'background-color':isDark?'#1c1c1c':'#f6f6f6','min-height':isDark?'100vh':'auto'}">
		<view class="header" :style="[{height:CustomBar + 'px'}]" :class="scrollTop>40?'goScroll':''">
			<view class="cu-bar" :class="scrollTop>40?(isDark?'color-white':'color-black'):'color-white'" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px', 'background-color': scrollTop>40?(isDark?'#1c1c1c !important':'#ffffff !important'):'transparent !important'}">
				<view class="action" @tap="back">
					<text class="cuIcon-back"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
					<block v-if="scrollTop>40">
						{{name || $t('global.unknowncircle')}}
					</block>
				</view>
				<!--  #ifdef H5 || APP-PLUS -->
				<view class="action">
					<text class="cuIcon-more" @click="show = true"></text>
					<tn-popup v-model="show" mode="bottom" :closeBtn="true"
						:height="myPurview>0&&group=='administrator'?'30%':'20%'" :borderRadius="20">
						<view class="center-container tn-margin-top-xxl" style="color: #333;">
							<view v-if="group=='administrator'||myPurview==5"
								class="tn-padding-sm tn-radius bg-flex-shadow popup-content sy-text-lg"
								@tap="toEdit(parent,id,name),show=false">
								<text class="tn-icon-write" style="margin-right: 5px;"></text>{{$t('forum.home.editcircle')}}
							</view>
							<view v-if="group=='administrator'||myPurview==5"
								class="tn-padding-sm tn-radius bg-flex-shadow popup-content sy-text-lg"
								@tap="moderator(id),show=false">
								<text class="tn-icon-team" style="margin-right: 5px;"></text>{{$t('forum.home.mgrcircleleader')}}
							</view>
							<view v-if="group=='administrator'||myPurview==5"
								class="tn-padding-sm tn-radius bg-flex-shadow popup-content sy-text-lg"
								@tap="setModerator(id,name),show=false">
								<text class="tn-icon-my-add" style="margin-right: 5px;"></text>{{$t('forum.home.addcircleowner')}}
							</view>
							<view class="tn-padding-sm tn-radius bg-flex-shadow popup-content sy-text-lg"
								v-if="isFollow==0" @tap="sectionFollow(1),show=false">
								<text class="tn-icon-add-circle" style="margin-right: 5px;"></text>{{$t('forum.home.joincircle')}}
							</view>
							<view class="tn-padding-sm tn-radius bg-flex-shadow popup-content sy-text-lg" v-else
								@tap="sectionFollow(0),show=false">
								<text class="tn-icon-close-circle" style="margin-right: 5px;"></text>{{$t('forum.home.exitcircle')}}
							</view>

						</view>
					</tn-popup>

				</view>
				<!--  #endif -->
			</view>
		</view>
		<view class="all-box" style="margin-top:-10upx">
			<view class="section-info" :style="'padding-top:'+NavBar+'px;'">
				<view class="section-info-bg">
					<image :src="bg" mode="aspectFill" style="height: 100%"></image>
				</view>
				<view class="section-info-main">
					<view class="section-info-content">
						<view class="section-info-full">
							<view class="section-info-ico" :class="{
								  'img-border-radius-10': radiusBoxStyle == 1,
								  'img-border-radius-32 ': radiusBoxStyle == 2,
								  'img-border-radius-50': radiusBoxStyle == 3
								}">
								<!-- <image src="../../static/h5/owo/img/paopao/E985B7_2x.png"></image> -->
								<image :src="pic" mode="aspectFill"></image>
								
							</view>
							<view class="section-info-intro grid col-2" style="height: 70px;margin: auto;">
								<view>
									<view class="section-info-title text-content-1">{{name || $t('global.unknowncircle')}}</view>
									<view class="text-content-2">{{$text}}</view>
								</view>
								<view class="section-info-value"
									style="display: flex;align-items: center;justify-content: flex-end">
									<block v-if="isFollow==0">
										<view class="cu-btn text-blue"
											style="background-color: #fff;border-radius: 10px;padding: 0 10px;font-size: 12px;height: 30px;color: #333;"
											@tap="sectionFollow(1)">
											<text class="tn-icon-add-circle margin-right-xs"></text>{{$t('global.join')}}
										</view>
									</block>
									<block v-else>
										<view class="cu-btn text-blue"
											style="background-color: #fff;border-radius: 10px;padding: 0 10px;font-size: 12px;height: 30px;color: #333;"
											v-if="isClock==0" @tap="sectionClock()"><text
												class="tn-icon-calendar margin-right-xs"></text>{{$t('global.signin')}}</view>
										<view class="cu-btn bg-blue"
											style="background-color: #fff;border-radius: 10px;padding: 0 10px;font-size: 12px;height: 30px;color: #333;"
											v-else><text class="tn-icon-success-circle margin-right-xs"></text>{{$t('forum.home.signedin')}}
										</view>
									</block>

								</view>
							</view>
						</view>
						<view class="section-info-moderator grid col-2">
							<view class="section-info-moderator" @tap="goModerators(id)">
								<tn-avatar-group :lists="moderators" :dsof="false"
									:badge="false" badgeBgColor="white" txNum="7"></tn-avatar-group>
							</view>
							<view class="section-info-clock"
								style="display: flex;align-items: center;justify-content: flex-end;font-size: 12px;">
								<view>
									<view class="tn-padding-right-sm" style="margin-bottom: 15upx;"><text
											class="tn-icon-inventory" style="margin-right: 10upx;"></text>{{$t('global.post') + postNum + $t('global.item')}}</view>
									<view class="tn-padding-right-sm" style="margin-bottom: 15upx;"><text
											class="tn-icon-calendar" style="margin-right: 10upx;"></text>{{$t('global.signin') + clockNum + $t('forum.home.people')}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="forum-list" :style="{'background-color':isDark?'#1c1c1c':'#ffffff'}">

			<view class="forum-list-type">
				<tn-tabs :class="isDark?'dark':'bg-white'" :list="titlePostList" :isScroll="true" :current="current" name="tab-name"
					@change="change" :style="{'background-color':isDark?'#1c1c1c':'#ffffff'}"></tn-tabs>
			</view>
			<view class="forum-list-top" v-if="topList.length > 0"
				style="margin: 10upx 20upx 0upx 20upx;border-radius: 20upx;box-shadow: 0upx 0upx 50upx 0upx rgba(0, 0, 0, 0.075);">
				<view class="forum-top-box" v-for="(item,index) in topList" @tap="goInfo(item.id)" :key="index">
					<view class="forum-top-i">
						<text class="text-red" v-if="item.isTop=='1'">{{$t('global.top')}}</text>
						<text class="text-red" v-if="item.isTop=='2'">{{$t('forum.home.overall')}}</text>
					</view>
					<view class="forum-top-text">
						{{item.title}}
					</view>
				</view>
			</view>

			<view class="forum-list-main">
				<view class="no-data" v-if="postList.length==0">
					<text class="cuIcon-text"></text>{{$t('common.nodata')}}
				</view>
				<!-- 列表模式 -->
				<block v-if="viewMode === 'list'">
					<block v-for="(item,index) in postList" :key="index">
						<forumItem :item="item" :myPurview="myPurview" :sectionId="id"></forumItem>
					</block>
				</block>
				<!-- 瀑布流模式 -->
				<block v-else>
					<view class="forum-card-container">
						<view class="forum-card-column">
							<block v-for="(item,index) in leftColumnPosts" :key="'left-' + index">
								<forumCardItem :item="item" :showType="cardShowType"></forumCardItem>
							</block>
						</view>
						<view class="forum-card-column">
							<block v-for="(item,index) in rightColumnPosts" :key="'right-' + index">
								<forumCardItem :item="item" :showType="cardShowType"></forumCardItem>
							</block>
						</view>
					</view>
				</block>
				<view class="load-more" @tap="loadMore" v-if="dataLoad&&postList.length>0">
					<text>{{moreText}}</text>
				</view>
			</view>
		</view>
		<view v-if="scrollTop>40" class="forum-post-btn-2 tn-main-gradient-orange box-shadow-2" @tap="refresh()">
			<text class="tn-icon-refresh-simple" :class="isRefreshing ? 'refresh-rotating' : ''"></text>
		</view>
		<view v-if="scrollTop<=40" class="forum-post-btn-1 tn-main-gradient-orange box-shadow-2" @tap="refresh()">
			<text class="tn-icon-refresh-simple" :class="isRefreshing ? 'refresh-rotating' : ''"></text>
		</view>
		<view v-if="scrollTop>40" class="forum-post-btn-1 tn-main-gradient-blue box-shadow-1" @tap="totop()">
			<text class="tn-icon-totop"></text>
		</view>
		<view class="forum-post-btn tn-main-gradient-indigo" @tap="addPost()">
			<text class="tn-icon-edit-write"></text>
		</view>
		<!--加载遮罩-->
		<view class="loading" v-if="isLoading==0">
			<view class="loading-main">
				<image src="../../static/loading.gif"></image>
			</view>
		</view>
		<!--加载遮罩结束-->
		<view class="full-noLogin" v-if="isuserlogin">
			<view class="full-noLogin-main">
				<view class="full-noLogin-text">
					{{$t('global.loginafterview')}}
				</view>
				<view class="full-noLogin-btn">
					<view class="cu-btn bg-blue" @tap="goLogin()">
						{{$t('global.loginnow')}}
					</view>
				</view>
			</view>
		</view>
		
		
	</view>
</template>

<script>
	import {
		localStorage
	} from '../../js_sdk/mp-storage/mp-storage/index.js'
	import darkModeMixin from '@/utils/darkModeMixin.js'
	import forumCardItem from '../components/forumCardItem.vue'
	import { shouldUseWaterfallMode, getCardShowType } from '../../utils/pageConfig.js'
	// #ifdef APP-PLUS
	import owo from '../../static/app-plus/owo/OwO.js'
	// #endif
	// #ifdef H5
	import owo from '../../static/h5/owo/OwO.js'
	// #endif
	// #ifdef MP
	var owo = [];
	// #endif
	export default {
		mixins: [darkModeMixin],
		components: {
			forumCardItem
		},
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar: this.StatusBar + this.CustomBar,
				AppStyle: this.$store.state.AppStyle,
				scrollTop: 0,
				id: 0,
				parent: 0,
				name: '',
				show: false,
				pic: '',
				isuserlogin:false,
				bg: '',
				slug: '',
				group: "",
				text: '',
				restrict: 0,
				postNum: 0,
				clockNum: 0,
				moderators: [],
				current: 1,
				viewMode: 'list', // 显示模式：list 列表模式，card 瀑布流模式（通过配置文件控制）
				cardShowType: 'views', // 卡片模式下显示的统计类型：views, comments, likes
				columnsCache: null, // 瀑布流列分配缓存
				titlePostList: [{
						order: "recommend",
						name: $t('global.essence'),
						parent: 0
					},{
						order: "created",
						name: $t('global.uptodate'),
						parent: 0
					}, 
					{
						order: "replyTime",
						name: $t('global.reply'),
						parent: 0
					},
					{
						order: "views",
						name: $t('global.hot'),
						parent: 0
					},
					{
						order: "likes",
						name: $t('global.like'),
						parent: 0
					}

				],
				orderKey: "created",
				isFollow: 0,
				isClock: 0,
				token: "",
				radiusBoxStyle: 0, 
				postList: [],
				topList: [],
				dataLoad: false,
				userInfo: null,
				page: 1,
				moreText: $t('common.loadmoretxt'),
				isLoading: 0,
				isHuaWei: this.$API.isHuaWei(),
				isTy: false,
				myPurview: 0,
				isvip:0,
				submitStatus1:false,
				submitStatus2:false,
				operateShow: false,
				isRefreshing: false // 刷新状态标记
			}
		},
		computed: {
			// 瀑布流左列数据
			leftColumnPosts() {
				if (this.viewMode !== 'card') return [];
				return this.distributePostsToColumns().left;
			},
			// 瀑布流右列数据
			rightColumnPosts() {
				if (this.viewMode !== 'card') return [];
				return this.distributePostsToColumns().right;
			}
		},
		onPageScroll(res) {
			var that = this;
			that.scrollTop = res.scrollTop;
		},
		onPullDownRefresh() {
			var that = this;
			// 执行常规刷新
			that.performRefresh();
		},
		onReachBottom() {
			//触底后执行的方法，比如无限加载之类的
			var that = this;
			if (that.isLoad == 0) {
				that.loadMore();
			}
		},
		onLoad(res) {
			var that = this;
			if (res.id) {
				that.id = res.id;
				// 根据配置文件决定显示模式
				try {
					that.viewMode = shouldUseWaterfallMode(res.id) ? 'card' : 'list';
					// 根据配置文件设置卡片显示类型
					that.cardShowType = getCardShowType(res.id);
				} catch (error) {
					that.viewMode = 'list';
					that.cardShowType = 'views';
				}
				that.getSectionInfo();
				that.getPostList(false);
				that.getTopList();
			}
			if(localStorage.getItem('userinfo')){
				var userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.isvip = userInfo.isvip;
			}
			that.userPurview();
			// #ifdef APP-PLUS || MP
			that.NavBar = that.CustomBar;
			// #endif
			that.page = 1;
			that.getSectionInfo();
		},
		onShow() {
			var that = this;
			uni.$emit('tOnLazyLoadReachBottom');
			if (localStorage.getItem('userinfo')) {
				that.userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.group = that.userInfo.group;
			} else {
				that.userInfo = null;
			}
			if (localStorage.getItem('token')) {
				that.token = localStorage.getItem('token');
			} else {
				that.token = "";
			}
			that.getSet();
			// 检查是否需要刷新帖子列表（仅在有新帖子时刷新）
			that.checkAndRefreshPosts();
			// #ifdef APP-PLUS
			//plus.navigator.setStatusBarStyle("dark")
			// #endif
		},
		mounted() {
			// #ifdef APP-PLUS
			this.initStatusBarStyle();
			// #endif
		},
		onHide() {
			var that = this;
			// 保存当前滚动位置，以便下次返回时恢复
			that.saveScrollPosition();
		},
		methods: {
			getSet() {
				var that = this;
				uni.request({
					url: that.$API.SPset(),
					method: 'GET',
					dataType: "json",
					success(res) {
						that.radiusBoxStyle = res.data.radiusStyle;
					},
					fail(error) {
						
					}
				})
			},
			// #ifdef APP-PLUS
			initStatusBarStyle() {
				var that = this;
				if (uni.getSystemInfoSync().platform === 'android') {
					plus.navigator.setStatusBarStyle('light'); // Android 平台
				} else {
					plus.navigator.setStatusBarStyle('light'); // iOS 平台
				}
			},
			onPageScroll(event) {
				this.scrollTop = event.scrollTop;
				if (this.scrollTop > 40) {
					if (uni.getSystemInfoSync().platform === 'android') {
						plus.navigator.setStatusBarStyle('dark'); // Android 平台
					} else {
						plus.navigator.setStatusBarStyle('dark'); // iOS 平台
					}
				} else {
					if (uni.getSystemInfoSync().platform === 'android') {
						plus.navigator.setStatusBarStyle('light'); // Android 平台
					} else {
						plus.navigator.setStatusBarStyle('light'); // iOS 平台
					}
				}
			},
			// #endif
			refresh() {
				var that = this;
				// 刷新按钮点击时，执行常规刷新
				that.performRefresh();
			},
			totop() {
				// 返回顶部操作
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
				window.scrollTo({
					top: 0,
					behavior: 'smooth', // Optional: add smooth scrolling behavior
				});
			},
			// #ifdef APP-PLUS
			//权限检测
			showTC(){
				var that = this;
				var tc1 = false;
				let _permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE';
				let _permissionID2 = 'android.permission.CAMERA';
				plus.android.checkPermission(_permissionID2,
					granted => {
						if (granted.checkResult == -1) {
							uni.showModal({
								title: that.$t('global.permissionapply'),
								content: that.$t('global.permissionapplydesc'),
								cancelText: that.$t('common.cancel'),
								confirmText: that.$t('global.agree'),
								showCancel: true,
								confirmColor: '#000',
								cancelColor: '#666',
								success: (res) => {
									if (res.confirm) {
										tc1 = true;
										that.requestPermissions();
									}else{
										that.isTy = false
										tc1 = true;
									}
								}
							})
							//还未授权当前查询的权限，打开权限申请目的自定义弹框
							that.$nextTick(() => {
								setTimeout(() => {
									that.ani = 'uni-' + that.type
								},30)
							})
						}
					},
					error => {
						console.log(error.message);
					}
				);
				plus.android.checkPermission(_permissionID,
					granted => {
						if (granted.checkResult == -1) {
							if(!tc1){
								uni.showModal({
									title: that.$t('global.permissionapply'),
									content: that.$t('global.permissionapplydesc'),
									cancelText: that.$t('common.cancel'),
									confirmText: that.$t('global.agree'),
									showCancel: true,
									confirmColor: '#000',
									cancelColor: '#666',
									success: (res) => {
										if (res.confirm) {
											return that.requestPermissions();
										}else{
											that.isTy = false
										}
									}
								})
							}
							//还未授权当前查询的权限，打开权限申请目的自定义弹框
							that.$nextTick(() => {
								setTimeout(() => {
									that.ani = 'uni-' + that.type
								},30)
							})
						}
					},
					error => {
						console.log(error.message);
					}
				);
				
			},
			requestPermissions() {
				let _this = this;
					let _permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE';
					let _permissionID2 = 'android.permission.CAMERA';
					plus.android.checkPermission(_permissionID2,
						granted => {
							if (granted.checkResult == -1) {
								//还未授权当前查询的权限，打开权限申请目的自定义弹框
								
								_this.$nextTick(() => {
									setTimeout(() => {
										_this.ani = 'uni-' + _this.type
									},30)
								})
							}
						},
						error => {
							
						}
					);
					plus.android.requestPermissions([_permissionID2],
						(e) => {
							//关闭权限申请目的自定义弹框
							_this.ani = '';
							_this.$nextTick(() => {
								
							})
							if (e.granted.length > 0) {
								//当前查询权限已授权
								plus.android.checkPermission(_permissionID,
									granted => {
										if (granted.checkResult == -1) {
											//还未授权当前查询的权限，打开权限申请目的自定义弹框
											
											_this.$nextTick(() => {
												setTimeout(() => {
													_this.ani = 'uni-' + _this.type
												},30)
											})
										}
									},
									error => {
										
									}
								);
								plus.android.requestPermissions([_permissionID],
									(e) => {
										//关闭权限申请目的自定义弹框
										_this.ani = '';
										_this.$nextTick(() => {
											
										})
										if (e.granted.length > 0) {
											//当前查询权限已授权
											_this.isTy = true
										}
										if (e.deniedAlways.length > 0) {
											//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
											uni.showModal({
												title: _this.$t('global.fogettips'),
												content: _this.$t('global.noalbumpermiss'),
												cancelText: _this.$t('common.cancel'),
												confirmText: _this.$t('global.setitup'),
												showCancel: true,
												confirmColor: '#000',
												cancelColor: '#666',
												success: (res) => {
													if (res.confirm) {
														_this.goSetting();
													}else{
														_this.isTy = false
													}
												}
											})
										}
									})
							}
							if (e.deniedAlways.length > 0) {
								//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
								uni.showModal({
									title: _this.$t('global.fogettips'),
									content: _this.$t('global.nocamerapermiss'),
									cancelText: _this.$t('common.cancel'),
									confirmText: _this.$t('global.setitup'),
									showCancel: true,
									confirmColor: '#000',
									cancelColor: '#666',
									success: (res) => {
										if (res.confirm) {
											_this.goSetting();
										}else{
											_this.isTy = false
										}
									}
								})
							}
						})
				
			},
			//跳转手机系统设置
			goSetting() {
				var Intent = plus.android.importClass("android.content.Intent");
				var Settings = plus.android.importClass("android.provider.Settings");
				var Uri = plus.android.importClass("android.net.Uri");
				var mainActivity = plus.android.runtimeMainActivity();
				var intent = new Intent();
				intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
				intent.setData(uri);
				mainActivity.startActivity(intent);
			},
			// #endif
			
			userStatus() {
				var that = this;
				that.$Net.request({
					url: that.$API.userStatus(),
					data: {
						"token": that.token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 0) {
							if (that.userInfo != null) {
								that.isLoginShow = true;
							}
							localStorage.removeItem('userinfo');
							localStorage.removeItem('token');
							that.userInfo = null;
						} else {
							if (localStorage.getItem('userinfo')) {
								var userInfo = JSON.parse(localStorage.getItem('userinfo'));
								if (res.data.data.group) {
									userInfo.group = res.data.data.group;
								}
								localStorage.setItem('userinfo', JSON.stringify(userInfo));
								// if(res.data.data.avatar){
								// 	that.userInfo = res.data.data.avatar;
								// }
							}
						}
					},
					fail: function(res) {
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			change(index) {
				var that = this;
				if (index == 2) {
					that.orderKey = 'created';
					that.current = index;
					that.orderKey = that.titlePostList[that.current].order;
					that.page = 1;
					that.getPostList(false);
				} else {
					that.current = index;
					that.orderKey = that.titlePostList[that.current].order;
					that.page = 1;
					that.getPostList(false);
				}
			},
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			formatDate(datetime) {
				var datetime = new Date(parseInt(datetime * 1000));
				// 获取年月日时分秒值  slice(-2)过滤掉大于10日期前面的0
				var year = datetime.getFullYear(),
					month = ("0" + (datetime.getMonth() + 1)).slice(-2),
					date = ("0" + datetime.getDate()).slice(-2),
					hour = ("0" + datetime.getHours()).slice(-2),
					minute = ("0" + datetime.getMinutes()).slice(-2);
				//second = ("0" + date.getSeconds()).slice(-2);
				// 拼接
				var result = year + "-" + month + "-" + date + " " + hour + ":" + minute;
				// 返回
				return result;
			},
			loadMore() {
				var that = this;
				that.moreText = that.$t('global.loading');
				that.isLoad = 1;
				that.getPostList(true);

			},
			goLogin() {
				uni.navigateTo({
					url: '/pages/user/login'
				});
			},
			getSectionInfo() {
				var that = this;
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				that.$Net.request({

					url: that.$API.sectionInfo(),
					data: {
						"id": that.id,
						"token": token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							that.name = res.data.data.name;
							that.pic = res.data.data.pic;
							that.bg = res.data.data.bg;
							that.parent = res.data.data.parent;
							that.slug = res.data.data.slug;
							that.text = res.data.data.text;
							that.restrict = res.data.data.restrictKey;
							that.moderators = res.data.data.moderators;
							that.postNum = res.data.data.postNum;
							that.clockNum = res.data.data.clockNum;
							that.isFollow = res.data.data.isFollow;
							that.isClock = res.data.data.isClock;
						}
					},
					fail: function(res) {
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			sectionFollow(type) {
				var that = this;
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				var data = {
					"sectionId": that.id,
					"token": token,
					"type": type
				}
				that.$Net.request({
					url: that.$API.sectionFollow(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						if (res.data.code == 1) {
							that.getSectionInfo();
						}

					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			sectionClock() {
				var that = this;
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				var data = {
					"sectionId": that.id,
					"token": token
				}
				that.$Net.request({
					url: that.$API.sectionClock(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						if (res.data.code == 1) {
							that.getSectionInfo();
						}

					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			addPost() {
				var that = this;
				if (!localStorage.getItem('token') || localStorage.getItem('token') == "") {
					uni.showToast({
						title: that.$t('common.plslogin'),
						icon: 'none'
					})
					return false;
				}
				if(that.isTy==false&&that.isHuaWei==1){
					that.showTC()
				}
				// 标记用户正在发帖，用于后续判断是否需要刷新
				localStorage.setItem('isPosting_' + that.id, 'true');
				uni.navigateTo({
					url: '/pages/edit/addPost?section=' + that.name + "&sectionid=" + that.id
				});
				// uni.navigateTo({
				// 	url: '/pages/forum/addPost?section='+that.name+"&sectionid="+that.id
				// });
			},
			moderator(id) {
				var that = this;
				if (!localStorage.getItem('token') || localStorage.getItem('token') == "") {
					uni.showToast({
						title: that.$t('common.plslogin'),
						icon: 'none'
					})
					return false;
				}
				uni.navigateTo({
					url: '/pages/manage/moderator?id=' + id
				});
			},
			setModerator(id, name) {
				var that = this;
				if (!localStorage.getItem('token') || localStorage.getItem('token') == "") {
					uni.showToast({
						title: that.$t('common.plslogin'),
						icon: 'none'
					})
					return false;
				}
				uni.navigateTo({
					url: '/pages/manage/setModerator?id=' + id + '&resOf=true&name=' + name
				});
			},
			getTopList() {
			    var that = this;
			    var token = "";
			    if (localStorage.getItem('userinfo')) {
			        var userInfo = JSON.parse(localStorage.getItem('userinfo'));
			        token = userInfo.token;
			    }
			    var globalData = {
			        "status": "1",
			        "isTop": '2'
			    };
			    that.$Net.request({
			        url: that.$API.postList(),
			        data: {
			            "searchParams": JSON.stringify(that.$API.removeObjectEmptyKey(globalData)),
			            "limit": 5,
			            "page": 1,
			            "token": token
			        },
			        header: {
			            'Content-Type': 'application/x-www-form-urlencoded'
			        },
			        method: "post",
			        dataType: 'json',
			        success: function(globalRes) {
			            if (globalRes.data.code == 1) {
			                var globalTopList = globalRes.data.data.map(item => {
			                    item.isTop = '2';
			                    return item;
			                });
			                var sectionData = {
			                    "section": that.id,
			                    "status": "1",
			                    "isTop": '1'
			                };
			                that.$Net.request({
			                    url: that.$API.postList(),
			                    data: {
			                        "searchParams": JSON.stringify(that.$API.removeObjectEmptyKey(sectionData)),
			                        "limit": 5,
			                        "page": 1,
			                        "token": token
			                    },
			                    header: {
			                        'Content-Type': 'application/x-www-form-urlencoded'
			                    },
			                    method: "post",
			                    dataType: 'json',
			                    success: function(sectionRes) {
			                        if (sectionRes.data.code == 1) {
			                            var sectionTopList = sectionRes.data.data.map(item => {
			                                item.isTop = '1';
			                                return item;
			                            });
			                            that.topList = globalTopList.concat(sectionTopList);
			                        }
			                    },
			                    fail: function(sectionRes) {
			                       
			                    }
			                });
			            }
			        },
			        fail: function(globalRes) {
			            
			        }
			    });
			},

			toEdit(parent, id, name) {
				uni.navigateTo({
					url: '/pages/manage/sectionEdit?parent=' + parent + '&sort=section&type=edit' + '&id=' + id + '&name=' + name
				});
			},
			getPostList(isPage,isLogin) {
				var that = this;
				var page = that.page;
				if(that.submitStatus1){
					return false;
				}
				that.submitStatus1 = true;
				var token = "";
				if(!isLogin){
					localStorage.setItem('isbug','1');
				}
				if (isPage) {
					page++;
				}
				var data = {
					"section": that.id,
					"status": "1",
					"isTop": '0',
				}
				var order = that.orderKey;
				if (order == 'recommend') {
					data.isrecommend = 1;
					that.orderKey = 'created'
				} else {
					data.order = order;
				}
				that.$Net.request({
					url: that.$API.postList(),
					data: {
						"searchParams": JSON.stringify(that.$API.removeObjectEmptyKey(data)),
						"limit": 10,
						"page": page,
						"order": that.orderKey,
						"token": token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if(!isLogin){
							localStorage.removeItem('isbug');
						}
						that.submitStatus1 = false;
						that.isLoad = 0;
						if (res.data.code == 1) {
							var list = res.data.data;
							if (list.length > 0) {
								var num = res.data.data.length;
								var rand = Math.floor(Math.random() * num);
								var pushAdsInfo = null;
								// #ifdef APP-PLUS || H5
								if(that.isvip==0){
									if(localStorage.getItem('pushAds')){
										var pushAds = JSON.parse(localStorage.getItem('pushAds'));
										var adsNum = pushAds.length;
										if(adsNum>0){
											var adsRand = Math.floor(Math.random()*adsNum);
											pushAdsInfo = pushAds[adsRand];
											pushAdsInfo.isAds = 1;
										}
									}
								}
								// #endif
								var postList = [];
								for (var i in list) {

									list[i].isAds = 0;
									postList.push(list[i]);
									// #ifdef APP-PLUS || H5
									var isAds = Math.round(Math.random());
									if (isAds == 1) {
										if (i == rand && pushAdsInfo != null) {
											postList.push(pushAdsInfo);
										}
									}
									// #endif
								}
								if (isPage) {
									that.page++;
									that.postList = that.postList.concat(postList);
								} else {
									that.postList = postList;
								}
								// 清除瀑布流缓存
								that.columnsCache = null;
							} else {
								if (isPage) {
									that.moreText = that.$t('common.nomoredata');
								} else {
									that.postList = [];
								}

							}
						} else {
							if (res.data.msg == "用户未登录或Token验证失败") {
								if (isLogin) {
									that.isuserlogin = true
								}else{
									that.getPostList(isPage, true);
								}
							}
						}
						var timer = setTimeout(function() {
							that.isLoading = 1;
							clearTimeout('timer')
						}, 300)
						that.isLoading = 1;
					},
					fail: function(res) {
						if(!isLogin){
							localStorage.removeItem('isbug');
						}
						that.submitStatus1 = false;
						that.isLoad = 0;
						that.moreText = that.$t('common.loadmoretxt');
						var timer = setTimeout(function() {
							that.isLoading = 1;
							clearTimeout('timer')
						}, 300)
						that.isLoading = 1;
					}
				})
			},
			userPurview() {
				var that = this;
				var uid = 0;
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					uid = userInfo.uid;
				}
				var data = {
					"uid": uid,
				}
				that.$Net.request({
					url: that.$API.userPurview(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							var list = res.data.data;
							if (list.length > 0) {
								for (var i in list) {
									if (list[i].sectionId == that.id) {
										that.myPurview = list[i].purview;
									}
								}
							}
							if (localStorage.getItem('userinfo')) {
								var myInfo = JSON.parse(localStorage.getItem('userinfo'));
								if (myInfo.group == 'administrator' || myInfo.group == 'editor') {
									that.myPurview = 5;
								}
							}
						}
					},
					fail: function(res) {

					}
				})
			},
			toSearch() {
				uni.redirectTo({
					url: '/pages/contents/search'
				});
			},
			goInfo(id) {
				uni.navigateTo({
					url: '/pages/forum/info?id=' + id
				});
			},
			goModerators(id){
				uni.navigateTo({
					url: '/pages/forum/moderators?id='+id
				});
			},
			// 智能分配帖子到左右两列，尽量保持高度平衡
			distributePostsToColumns() {
				// 如果缓存存在且数据没有变化，直接返回缓存
				if (this.columnsCache && this.columnsCache.postListLength === this.postList.length) {
					return this.columnsCache.columns;
				}
				const posts = this.postList;
				const left = [];
				const right = [];
				let leftHeight = 0;
				let rightHeight = 0;
				
				posts.forEach(post => {
					// 估算每个帖子的高度
					const estimatedHeight = this.estimatePostHeight(post);
					
					// 选择高度较小的一列
					if (leftHeight <= rightHeight) {
						left.push(post);
						leftHeight += estimatedHeight;
					} else {
						right.push(post);
						rightHeight += estimatedHeight;
					}
				});
				
				const result = { left, right };
				
				// 缓存结果
				this.columnsCache = {
					postListLength: posts.length,
					columns: result
				};
				
				return result;
			},
			// 估算帖子高度（用于瀑布流布局）
			estimatePostHeight(post) {
				const baseHeight = 180; // 标题和底部信息的基础高度
				let imageHeight = 250; // 默认图片高度
				
				// 根据帖子内容类型估算图片高度
				if (post.images && post.images.length > 0) {
					// 有图片的帖子，根据标题长度调整预估高度
					const titleLength = post.title ? post.title.length : 0;
					if (titleLength > 30) {
						imageHeight = 300; // 标题长的帖子可能图片也比较高
					} else if (titleLength < 15) {
						imageHeight = 200; // 标题短的帖子图片可能比较矮
					}
				} else if (post.videos && post.videos.length > 0) {
					imageHeight = 280; // 视频封面通常是16:9比例
				} else {
					imageHeight = 300; // 无图片时使用占位图
				}
				
				return baseHeight + imageHeight;
			},
			// 执行常规刷新（下拉刷新、刷新按钮）
			performRefresh() {
				var that = this;
				// 防止重复刷新
				if (that.isRefreshing) {
					uni.showToast({
						title: that.$t('forum.home.refreshprogrein'),
						icon: 'none',
						duration: 1000
					});
					return;
				}
				// 设置刷新状态
				that.isRefreshing = true;
				// 重置页码
				that.page = 1;
				// 清除瀑布流缓存
				that.columnsCache = null;
				// 显示加载提示
				uni.showToast({
					title: that.$t('forum.home.refreshprogre'),
					icon: 'loading',
					duration: 1000
				});
				// 刷新所有数据
				that.getSectionInfo();
				that.getPostList(false);
				that.getTopList();
				// 常规刷新完成后回到顶部
				setTimeout(function() {
					// 重置刷新状态
					that.isRefreshing = false;
					uni.stopPullDownRefresh();
					// 滚动到顶部
					// #ifdef APP-PLUS
					uni.pageScrollTo({
						scrollTop: 0,
						duration: 300
					});
					// #endif
					// #ifdef H5
					window.scrollTo({
						top: 0,
						behavior: 'smooth'
					});
					// #endif
					// #ifdef MP
					uni.pageScrollTo({
						scrollTop: 0,
						duration: 300
					});
					// #endif
					uni.showToast({
						title: that.$t('forum.home.completrefresh'),
						icon: 'success',
						duration: 1000
					});
				}, 1200);
			},
			// 检查是否需要刷新帖子列表（发帖后返回）
			checkAndRefreshPosts() {
				var that = this;
				// 检查是否有新帖子发布的标记
				var needRefresh = localStorage.getItem('needRefreshPosts_' + that.id);
				if (needRefresh === 'true') {
					// 执行智能刷新（保持位置）
					that.performSmartRefresh();
				}
			},
			// 执行智能刷新（保持用户浏览位置）
			performSmartRefresh() {
				var that = this;
				// 防止与常规刷新冲突
				if (that.isRefreshing) {
					// 如果正在常规刷新，延迟执行智能刷新
					setTimeout(() => {
						that.performSmartRefresh();
					}, 1500);
					return;
				}
				// 记录当前滚动位置
				that.saveScrollPosition();
				// 重置页码并清除缓存
				that.page = 1;
				that.columnsCache = null;
				// 刷新数据
				that.getSectionInfo();
				that.getPostList(false);
				that.getTopList();
				// 清除刷新标记
				localStorage.removeItem('needRefreshPosts_' + that.id);
				// 延迟恢复滚动位置并显示成功提示
				setTimeout(() => {
					that.restoreScrollPosition();
				}, 600);
			},
			// 保存滚动位置
			saveScrollPosition() {
				var that = this;
				localStorage.setItem('scrollPosition_' + that.id, that.scrollTop.toString());
			},
			// 恢复滚动位置
			restoreScrollPosition() {
				var that = this;
				var savedPosition = localStorage.getItem('scrollPosition_' + that.id);
				if (savedPosition) {
					var scrollTop = parseInt(savedPosition);
					// 使用nextTick确保DOM已更新
					that.$nextTick(() => {
						setTimeout(() => {
							// #ifdef APP-PLUS
							uni.pageScrollTo({
								scrollTop: scrollTop,
								duration: 0 // 无动画，直接跳转
							});
							// #endif
							// #ifdef H5
							window.scrollTo({
								top: scrollTop,
								behavior: 'auto'
							});
							// #endif
							// #ifdef MP
							uni.pageScrollTo({
								scrollTop: scrollTop,
								duration: 0
							});
							// #endif
						}, 100);
					});
				}
			}
		}
	}
</script>

<style>
	.forum-post-btn-1 {
		position: fixed;
		z-index: 888;
		bottom: 200upx;
		right: 60upx;
		width: 90upx;
		height: 90upx;
		font-size: 40upx;
		color: #fff;
		border-radius: 50%;
		text-align: center;
		line-height: 90upx;
	}

	.forum-post-btn-2 {
		position: fixed;
		z-index: 888;
		bottom: 300upx;
		right: 60upx;
		width: 90upx;
		height: 90upx;
		font-size: 40upx;
		color: #fff;
		border-radius: 50%;
		text-align: center;
		line-height: 90upx;
	}
	.box-shadow-1 {
		box-shadow: 0 0 10upx #31C9E8bf;
	}
	.box-shadow-2 {
		box-shadow: 0 0 10upx #Ff9700bf;
	}

	.text-content-1 {
		overflow: hidden;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
	}

	.text-content-2 {
		font-size: 22upx;
		overflow: hidden;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.img-border-radius-10 image {
		border-radius: 20upx;
	}

	.img-border-radius-32 image {
		border-radius: 44upx;
	}

	.img-border-radius-50 image {
		border-radius: 50%;
	}

	.tn-margin-top-xxl {
		margin-top: 60upx;
	}

	.center-container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}



	.forum-card-container {
		display: flex;
		padding: 20upx;
		gap: 20upx;
	}

	.forum-card-column {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	/* 刷新按钮旋转动画 */
	.refresh-rotating {
		animation: refresh-spin 1s linear infinite;
	}

	@keyframes refresh-spin {
		0% {
			transform: rotate(0deg);
		}
		100% {
			transform: rotate(360deg);
		}
	}
</style>